package com.letou.ls.uitl;

import java.io.File;

import org.apache.table.JsonUtil;

import com.letou.ls.mode.VersionInfo;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.KeyEvent;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.HttpHandler;

public class VersionUpdate {
	private static FinalHttp fh = null;
	private static Context mContext;

	private static ProgressDialog pd;

	public static void versionLoad(Context context) {

		if (TextUtils.isEmpty(Constant.token)) {
			return;
		}
		mContext = context;
		// String strJson = getVersionStr();

		fh = new FinalHttp();

		String url = Constant.URL_SERVER_VERSION + "?token=" + Constant.token;
		Logger.v("lss", url);
		// 获取IMEI
		fh.configTimeout(30000);
		fh.get(url, new AjaxCallBack<String>() {
			@Override
			public void onSuccess(String strJson) {

				// 登陆结果转换
				VersionInfo version = JsonUtil.fromJson(strJson, VersionInfo.class);

				Logger.v("lss", version.toString());
				Logger.v("lss", Constant.getCurrentVersion(mContext));
				Logger.v("lss", version.getVersion());

				if (version.toString() == null) {
					return;
				}
				if (Constant.getCurrentVersion(mContext).equals(version.getVersion())) {
					return;
				}
				String[] array = version.getVersion().split("\\.");
				String[] oldArray = Constant.getCurrentVersion();
//				Logger.v("lss", "  " + array.length + "  " + oldArray.length);
				int size = array.length < oldArray.length ? array.length : oldArray.length;

				boolean isUpdate = false;

				for (int index = 0; index < size; index++) {
//					Logger.v("lss",
//							"isUpdate   " + Integer.valueOf(array[index]) + " " + Integer.valueOf(oldArray[index]));
					if (Integer.valueOf(array[index]) > Integer.valueOf(oldArray[index])) {
						isUpdate = true;
						break;
					} else if (Integer.valueOf(array[index]) < Integer.valueOf(oldArray[index])) {
						isUpdate = false;
						break;
					}

				}

				if (isUpdate) {
					if ("true".equals(version.getForceUpdate())) {
						downloadApk(version.getDownloadUrl());
					} else {
						showUpdataDialog(version.getDownloadUrl(), version.getTitle(), version.getRemarks());
					}
				}

				// 登陆失败
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO
			}

		});

	}

	private static AlertDialog alertDialog;

	/**
	 * 
	 * 弹出对话框通知用户更新程序
	 */
	private static void showUpdataDialog(final String serverFilePath, String title, String message) {

		if (TextUtils.isEmpty(serverFilePath)) {
			return;
		}
		if (pd != null && pd.isShowing()) {
			return;
		}
		alertDialog = new AlertDialog.Builder(mContext).setTitle(title).setMessage(message)
				.setOnKeyListener(new OnKeyListener() {
					//
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						// TODO Auto-generated method stub
						if (keyCode == KeyEvent.KEYCODE_BACK) {
							dialog.dismiss();
						}
						return false;
					}

				}).setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						downloadApk(serverFilePath);
						dialog.dismiss();
					}
				}).setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).create();
		alertDialog.show();
	}

	/**
	 * 下载最新软件包
	 * 
	 * @param serverPath
	 * @param localPath
	 */
	private static void downloadApk(String serverPath) {
		if (TextUtils.isEmpty(serverPath)) {
			return;
		}
		pd = new ProgressDialog(mContext);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setMessage("正在下载更新");
		pd.setCanceledOnTouchOutside(false);
		pd.show();

		String sdcardPath = Constant.getSDCardPath() + Constant.getName(serverPath);
		// VersionInfo [code=200, message=, version=2.0, title=新春版，财运亨通！,
		// remarks=新年贺岁，恭喜发财版。祝大家好运连连！,
		// downloadUrl=http://119.10.9.19:8080/install/Letou_2_0.apk,
		// releaseTime=2016-01-20 21:42:05, forceUpdate=false]

		fh = new FinalHttp();
		fh.configTimeout(300000);
		// 调用download方法开始下载
		HttpHandler<File> handler = fh.download(serverPath, // 这里是下载的路径
				sdcardPath, false, // true:断点续传 false:不断点续传（全新下载）
				new AjaxCallBack<File>() {
					@Override
					public void onLoading(long count, long current) {
						pd.setMax((int) count / 1024);
						pd.setProgress((int) current / 1024);
					}

					@Override
					public void onSuccess(File t) {
						pd.dismiss();
						if (t != null) {
							installApk(t);
						}
					}

					@Override
					public void onFailure(Throwable t, int errorNo, String strMsg) {
						pd.dismiss();
						// loginProcess();
						Logger.v("main", "onFailure   = " + errorNo + "    " + strMsg);
					}
				});
	}

	/**
	 * 安装软件
	 * 
	 * @param file
	 */
	private static void installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		mContext.startActivity(intent);
	}

}
